<?php

namespace model\service;

use api\request\DomainQueryRequest;
use model\repo\DropCatch;

class DomainService
{
    public function query(/* array */$params) {
        $where = array();
        // 域名包含
        if (isset($params['domain'])) {
            $domain = $params['domain']['contains'];
            $where[] = $this->getKwCond("domain", $domain, intval($params['domain']['pos']));
        }
        // 域名删除日期
        if (isset($params['deletion_date'])) {
            $where[] = "deletion_date='".$params['deletion_date']."'";
        }
        $page = isset($params['page'])?intval($params['page']) : 1;
        $size = isset($params['size'])?intval($params['size']) : 10;
        $dropCatch = new DropCatch();
        $p = $dropCatch->paginate($where, $page, $size);
        foreach($p['data'] as &$t) {
            $t['length'] = intval($t['length']);
            $t['sogou_record'] = intval($t['sogou_record']);
        }
        return $p;
    }

    private function getKwCond(/* string */$name, /* string */$value, /* int */$pos) {
        switch ($pos) {
            case DomainQueryRequest::POS_BEGIN:
                $cond = sprintf("`%s` REGEXP '^%s'", $name, addslashes($value));
                break;
            case DomainQueryRequest::POS_END:
                $cond = sprintf("`%s` REGEXP '%s$'", $name, addslashes($value));
                break;
            case DomainQueryRequest::POS_MIDDLE:
                $cond = sprintf("`%s` LIKE '%%%s%%'", $name, addslashes($value));
                break;
            default:
                $cond = sprintf("`%s`='%s'", $name, addslashes($value));
        }
        return $cond;
    }
}